package com.fcy.teamwork.business.recommendstudent

import androidx.lifecycle.ViewModel
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.model.Conversation
import com.fcy.teamwork.App
import com.fcy.teamwork.pojo.Job
import com.fcy.teamwork.pojo.Person
import com.fcy.teamwork.pojo.SingleConversation
import com.fcy.teamwork.pojo.TeamWorkResult
import com.fcy.teamwork.repo.RetrofitClient
import retrofit2.http.Body
import retrofit2.http.POST

class RecommendStudentVM : ViewModel() {
    interface Recommend {
        @POST("/sms/recommend/loadRecommendStudents")
        suspend fun loadRecommendStudents(@Body job: Job): TeamWorkResult<List<Person>>

        @POST("/sms/recommend/createInvitation")
        @JvmSuppressWildcards
        suspend fun createInvitation(@Body conversations: List<SingleConversation>): TeamWorkResult<Boolean>
    }

    private val service = RetrofitClient.getService<Recommend>()

    suspend fun loadRecommends(job: Job): List<Person> {
        val res = service.loadRecommendStudents(job)
        return if (res.isOk) {
            res.data
        } else emptyList()
    }

    suspend fun sendInvitation(persons: List<Person>, job: Job) {
        service.createInvitation(persons.map {
            SingleConversation(null, App.person.id, it.id).apply {
                val conversation = Conversation.createSingleConversation(it.id.toString())
                val msg =
                    conversation.createSendCustomMessage(mutableMapOf<String?, String?>().apply {
                        put("type", "1")
                        put("jobId", job.id.toString())
                    })
                JMessageClient.sendMessage(msg)
            }
        }.toList())
    }
}